package com.smforj.ssm.modules.api.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletInputStream;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smforj.ssm.frame.core.enums.RouterMapping;
import com.smforj.ssm.frame.core.web.controller.BaseControllerSupportImpl;
import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.modules.lib.domain.CheckInResponse;
import com.smforj.ssm.modules.lib.domain.CheckOutResponse;
import com.smforj.ssm.modules.lib.domain.EditingLog;
import com.smforj.ssm.modules.lib.domain.EditingRequest;
import com.smforj.ssm.modules.lib.domain.ItemResponse;
import com.smforj.ssm.modules.lib.domain.LibraryRequest;
import com.smforj.ssm.modules.lib.domain.SysBook;
import com.smforj.ssm.modules.lib.domain.SysConfig;
import com.smforj.ssm.modules.lib.domain.vo.SysBookVo;
import com.smforj.ssm.modules.lib.service.BookInfoService;
import com.smforj.ssm.modules.lib.service.EditingLogService;
import com.smforj.ssm.modules.lib.service.LibraryService;
import com.smforj.ssm.modules.lib.service.SysConfigService;
import com.smforj.ssm.modules.sys.service.SysReaderService;
import com.smforj.ssm.util.PropKit;

import net.sf.json.JSONObject;

@RouterMapping("")
@Controller
@RequestMapping("/library/api/sip")
public class RworkStationControllerForSip2 extends BaseControllerSupportImpl {
    private Logger log = Logger.getLogger(this.getClass());

    @Autowired
    @Qualifier("sysBookInfoService")
    private BookInfoService bookInfoService;
    @Autowired
    @Qualifier("editingLogService")
    private EditingLogService editingLogService;
    @Autowired
    @Qualifier("libraryService")
    private LibraryService libraryService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    @Qualifier("sysReaderService")
    private SysReaderService sysReaderService;


    /***
     * 上传数据测试
     * @return
     * @date 2016-8-11 下午2:03:45
     */
    @RequestMapping(value = {"/datatest"}, method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<EditingRequest> doUploadEditingDataTest(String str) {
        System.out.println("RWorkStationController doUploadEditingDataTest");
        EditingRequest book = new EditingRequest();
        book.setSzUserId(str);
        List<SysBook> list = new ArrayList<SysBook>();
        list.add(new SysBook());
        book.setBooks(list);
        return new DataResult<EditingRequest>(DataResult.DataStatus.OK, "", book);
    }

    /*****
     * 上传采编信息,已经采编过的将进行更新
     * @param request 采编请求对象
     * @return
     * @date 2017-9-14 上午9:23:59
     */
    @RequestMapping(value = {"/data/upload"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<ItemResponse>> doUploadEditingData(@RequestBody EditingRequest request) {
        System.out.println("RWorkStationController doUploadEditingData");
        //返回全部采编信息
        DataResult<List<ItemResponse>> result = new DataResult<List<ItemResponse>>();
        if (request == null || request.getBooks() == null) {
            result.addError("无上传信息");
            return result;
        }
        List<ItemResponse> list = new ArrayList<ItemResponse>();
        ItemResponse item = null;
        for (int i = 0; i < request.getBooks().size(); i++) {
            item = new ItemResponse();
            SysBook book = request.getBooks().get(i);
            log.info("barcode" + book.getBarcode());

            item.setBarcode(book.getBarcode());
            item.setRfid(book.getRfid());
            book.setUpdate_date(new Timestamp(System.currentTimeMillis()));
            try {
                SysBook sbook = bookInfoService.queryBook(book.getRfid(), book.getBarcode());
                //已经存在的将不进行保存数据
                if (sbook == null) {
                    //保存日志
                    EditingLog entity = new EditingLog();
                    entity.setBook_id(book.getBarcode());
                    //entity.setWorkdate((new SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
                    //entity.setUser(request.getSzUserId());
                    editingLogService.insert(entity);

                    //保存图书信息
                    sbook = new SysBook();
                    sbook.setBarcode(book.getBarcode());
                    sbook.setRfid(book.getRfid());
                    bookInfoService.insert(book);
                } else {
                    //rfid不一样时进行更新
                    if (!sbook.getRfid().equalsIgnoreCase(book.getRfid())) {
                        //更新图书信息
                        book.setBarcode(book.getBarcode());
                        book.setRfid(book.getRfid());
                        bookInfoService.updateByIdSelective(book);
                    }
                    //RFID一样时不在该方法内处理
                }
                item.addOK("上传数据成功");
                list.add(item);

            } catch (Exception ex) {
                log.error("上传数据失败: " + ex.getMessage());
                item.addError("上传数据失败");
                list.add(item);
            }
        }
        result.addOK("", list);
        return result;
    }

    /***
     * 上传数据
     * @return
     * @date 2016-8-11 下午2:03:45
     */
    @RequestMapping(value = {"/data"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult doUploadEditingData() {
        System.out.println("RWorkStationController doUploadEditingData");
        try {
            String json = getInputStram();
            log.info(json);

            JSONObject jsonObject = JSONObject.fromObject(json);

            String barcode = jsonObject.getString("Barcode");

            log.info("barcode" + barcode);
            SysBook query = new SysBook();
            query.setBarcode(barcode);
            SysBook book = bookInfoService.queryOne(query);
            //已经存在的将不进行保存数据
            if (book == null) {
                LibraryRequest libreq = new LibraryRequest();
                //libreq.setBookid(barcode);
                SysConfig sc = sysConfigService.selectByPrimaryKey(PropKit.get("sysid"));
                //libreq.setSysConfig(sc);
                System.out.println(sc);
                ItemResponse itemResponse = libraryService.getBookInfo(libreq);
                if (itemResponse.getStatus() == 1) {
                    //保存日志
                    EditingLog entity = new EditingLog();
                    entity.setBook_id(barcode);
                    //entity.setWorkdate((new SimpleDateFormat("yyyy-MM-dd")).format(new Date()));
                    //entity.setUser(jsonObject.getString("User"));
                    editingLogService.insert(entity);

                    //保存图书信息
                    book = new SysBook();
                    book.setBarcode(barcode);
                    book.setRfid(jsonObject.getString("EPC"));
                    //book.setAuthor(itemResponse.getPublisher());
                    book.setBookname(itemResponse.getBookName());
                    //book.setCallnum(itemResponse.getCallNum());
                    //book.setLibname(itemResponse.getLocation());
                    bookInfoService.insert(book);
                    return new DataResult(DataResult.DataStatus.OK, "上传数据成功," + book.getBarcode());
                } else
                    return new DataResult(DataResult.DataStatus.ERROR, "上传数据失败找不到相应的图书信息");
            } else
                return new DataResult(DataResult.DataStatus.OK, "数据已经上传过");
        } catch (Exception ex) {
            log.error("上传数据失败: " + ex.getMessage());
            return new DataResult(DataResult.DataStatus.ERROR, "上传数据失败: " + ex.getMessage());
        }
    }


    /**
     * 图书查询
     *
     * @return
     */
    @RequestMapping(value = {"/data/searchbook/{id}"}, method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<ItemResponse>> doSearchBook(@PathVariable("id") String id) {
        System.out.println("RWorkStationController getRecord");
        DataResult<List<ItemResponse>> result = new DataResult<List<ItemResponse>>();
        List<ItemResponse> list = new ArrayList<ItemResponse>();
        SysBookVo sbook = new SysBookVo();
        ItemResponse item = new ItemResponse();
/*        try {
            SysBookVo sBook = bookInfoService.selectBookByRfid(id);
            if (sbook == null) {
                item.setStatus(0);
                item.setMessage("无该图书");
                result.addError(item.getMessage());
            } else {
                LibraryRequest request = new LibraryRequest();
                SysConfig sc = new SysConfig();
                sc.setSip2ip(PropKit.get("sip2ip"));
                sc.setSip2port(Integer.parseInt(PropKit.get("sip2port")));
                sc.setLibtype(0);
                request.setSysConfig(sc);
                List<SysBook> bookList = new ArrayList<SysBook>();
                bookList.add(sBook);
                request.setBookList(bookList);
                item = libraryService.getBookInfo(request);
                item.setBarcode(sBook.getBarcode());
                item.setRfid(sBook.getRfid());
                if (item.getStatus() == 0)
                    result.addError(item.getMessage());
                else {
                    list.add(item);
                    result.addOK("", list);
                }
            }
        } catch (Exception e) {
            log.error("查询失败: " + e.getMessage());
//            DataResult test2 =  new DataResult(DataStatus.ERROR, "查询失败: " + e.getMessage());
            result.addError("查询失败");
            return result;
        }*/
        result.addOK("", list);
        return result;
    }


    /***
     * 借阅
     * @return
     * @date
     */
    @RequestMapping(value = {"/eslibrary/checkout"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckOutResponse>> doCheckout(@RequestBody LibraryRequest request) {
        System.out.println("BusinessController doCheckout");
        List<SysBook> barcodeList = new ArrayList<SysBook>();
        DataResult<List<CheckOutResponse>> result = new DataResult<List<CheckOutResponse>>();
/*        for (SysBook book : request.getBookList()) {
            SysBookVo sysBookVo = bookInfoService.selectBookByRfid(book.getRfid());
            if (sysBookVo != null) {
                barcodeList.add(sysBookVo);
            }
        }
        SysReader sysReader = new SysReader();
        sysReader.setRfidCardNum(request.getSzUserId());
        sysReader = sysReaderService.queryOne(sysReader);
        if (barcodeList == null || barcodeList.size() == 0) {
            result.addError("查无此书");
        } else {
            SysConfig sc = new SysConfig();
            sc.setSip2ip(PropKit.get("sip2ip"));
            sc.setSip2port(Integer.parseInt(PropKit.get("sip2port")));
            sc.setLibtype(0);
            request.setSysConfig(sc);
            request.setBookList(barcodeList);
            if (sysReader == null) {
                result.addError("读者信息不正确");
            } else {
                request.setSzUserId(sysReader.getCampusCardNum());
                result.addOK("", libraryService.checkout(request));
            }
        }*/
        return result;
    }


    /***
     * 归还
     * @return
     * @date
     */
    @RequestMapping(value = {"/eslibrary/checkin"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckInResponse>> doCheckin(@RequestBody LibraryRequest request) {
        System.out.println("BusinessController doCheckin");
        List<SysBook> barcodeList = new ArrayList<SysBook>();
        DataResult<List<CheckInResponse>> result = new DataResult<List<CheckInResponse>>();
/*        for (SysBook book : request.getBookList()) {
            SysBookVo sysBookVo = bookInfoService.selectBookByRfid(book.getRfid());
            if (sysBookVo != null) {
                barcodeList.add(sysBookVo);
            }
        }
        if (barcodeList == null || barcodeList.size() == 0) {
            result.addError("查无此书");
        } else {
            SysConfig sc = new SysConfig();
            sc.setSip2ip(PropKit.get("sip2ip"));
            sc.setSip2port(Integer.parseInt(PropKit.get("sip2port")));
            sc.setLibtype(0);
            request.setSysConfig(sc);
            request.setBookList(barcodeList);
            result.addOK("", libraryService.checkin(request));
        }*/

        return result;
    }


    /***
     * 续借
     * @return
     * @date
     */
    @RequestMapping(value = {"/eslibrary/renew"}, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult<List<CheckOutResponse>> doRenew(@RequestBody LibraryRequest request) {
        System.out.println("BusinessController doRenew");
        List<SysBook> barcodeList = new ArrayList<SysBook>();

        DataResult<List<CheckOutResponse>> result = new DataResult<List<CheckOutResponse>>();
/*        for (SysBook book : request.getBookList()) {
            SysBookVo sysBookVo = bookInfoService.selectBookByRfid(book.getRfid());
            if (sysBookVo != null) {
                barcodeList.add(sysBookVo);
            }
        }
        SysReader sysReader = new SysReader();
        sysReader.setRfidCardNum(request.getSzUserId());
        sysReader = sysReaderService.queryOne(sysReader);
        if (barcodeList == null || barcodeList.size() == 0) {
            result.addError("查无此书");
        } else {
            SysConfig sc = new SysConfig();
            sc.setSip2ip(PropKit.get("sip2ip"));
            sc.setSip2port(Integer.parseInt(PropKit.get("sip2port")));
            sc.setLibtype(0);
            request.setSysConfig(sc);
            request.setBookList(barcodeList);
            if (sysReader == null) {
                result.addError("读者信息不正确");
            } else {
                request.setSzUserId(sysReader.getCampusCardNum());
                result.addOK("", libraryService.renew(request));
            }
        }*/
        return result;
    }

    /***
     * 获取工作统计信息
     * @return
     * @date 2016-8-11 下午2:03:45
     */
    @RequestMapping(value = {"/stat"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult getStatistics() {
        System.out.println("RWorkStationController getStatistics");
        try {
            String json = getInputStram();
            log.info(json);
            JSONObject jsonObject = JSONObject.fromObject(json);

            String user = jsonObject.getString("User");
            long iCount = editingLogService.getEditingCount(user);
            long iDate = editingLogService.getEditingDate(user);
            log.info("iCount: " + iCount + " iDate: " + iDate);
            jsonObject.clear();
            jsonObject.put("User", user);
            jsonObject.put("Date", iDate);
            jsonObject.put("SCount", iCount);

            return new DataResult(DataResult.DataStatus.OK, "", jsonObject);
        } catch (Exception ex) {
            log.error("统计数据失败: " + ex.getMessage());
            return new DataResult(DataResult.DataStatus.ERROR, "统计数据失败: " + ex.getMessage());
        }
    }

    /***
     * 同步采编信息
     * @return
     * @date 2016-8-11 下午2:03:45
     */
    @RequestMapping(value = {"/sync"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult doSynchronize() {
        System.out.println("RWorkStationController doSynchronize");
        try {
            String json = getInputStram();
            log.info(json);
            log.info("queryCount:  " + this.editingLogService.queryById("b341fbe0af9611e606c390e493286c74"));
            long iCount = editingLogService.getEditingCount(json);
            long iDate = editingLogService.getEditingDate(json);
            log.info("iCount: " + iCount + " iDate: " + iDate);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("User", json);
            jsonObject.put("Date", iDate);
            jsonObject.put("SCount", iCount);

            return new DataResult(DataResult.DataStatus.OK, "", jsonObject);
        } catch (Exception ex) {
            log.error("统计数据失败: " + ex.getMessage());
            return new DataResult(DataResult.DataStatus.ERROR, "统计数据失败: " + ex.getMessage());
        }
    }

    @RequestMapping(value = {"/synctest"}, method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataResult doSynchronizetest() {
        System.out.println("RWorkStationController doSynchronize");
        try {
            String json = getInputStram();
            log.info(json);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("User", json);

            return new DataResult(DataResult.DataStatus.OK, "", "");
        } catch (Exception ex) {
            log.error("统计数据失败: " + ex.getMessage());
            return new DataResult(DataResult.DataStatus.ERROR, "统计数据失败: " + ex.getMessage());
        }
    }

    /***
     * 读取流信息
     * @return
     * @throws IOException
     * @date 2016-11-21 下午2:03:01
     */
    private String getInputStram() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (ServletInputStream) this.request.getInputStream()));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }
}
